package org.apache.ocean.merge;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.ocean.CLong;
import org.apache.ocean.ClusterConstants;
import org.apache.ocean.ClusterUtil;
import org.apache.ocean.IndexSchema;
import org.apache.ocean.OceanDocument;
import org.apache.ocean.SearchRequest;
import org.apache.ocean.SearchRequestUtil;
import org.apache.ocean.SearchResponse;
import org.apache.ocean.TimeoutState;
import org.apache.ocean.util.PrintStringWriter;

/**
 * Make search ui servlet able to run on node or on merge server
 * 
 * @author jasonr
 */
public class MergeUIServlet extends HttpServlet {
	public static Logger log = Logger.getLogger(MergeUIServlet.class.getName());
	MergeService mergeService;

	public void init() throws ServletException {
		try {
			mergeService = MergeService.getMergeService();
		} catch (Throwable throwable) {
			log.log(Level.SEVERE, "", throwable);
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintStringWriter printStringWriter = new PrintStringWriter();
		try {
			response.setContentType(ClusterConstants.CONTENT_TYPE_HTML);
			handleSearchUI(request, printStringWriter);
		} catch (Throwable throwable) {
			log.log(Level.SEVERE, "", throwable);

		}
	}

	// TODO: guid needs cellid
	private void handleUpdateUI(HttpServletRequest request, PrintStringWriter writer) throws Exception {
		String id = request.getParameter(ClusterConstants.ID_FIELD);
		String shardID = request.getParameter(ClusterConstants.SHARD_ID_FIELD);
		String cellID = request.getParameter(ClusterConstants.CELL_ID_FIELD);

		if (ClusterUtil.isNotBlank("save", request)) {

		} else {

		}
	}

	private void handleSearchUI(HttpServletRequest request, PrintStringWriter writer) throws Exception {
		IndexSchema indexSchema = mergeService.getMergeNameClient().indexSchemaRef.get();
		MergeClient mergeClient = mergeService.getMergeClient();
		String queryString = "";
		String sort = "";
		String htmlEscapedQueryString = "";
		TimeoutState timeoutState = new TimeoutState(1000 * 5);
		if (ClusterUtil.isNotBlank("search", request)) {
			queryString = request.getParameter("q");
			sort = request.getParameter("sort");
		}
		writer.println("<form action='" + request.getRequestURI() + "' method=get>");
		writer.println("<table border=0>");
		writer.println("<tr><td>Search:</td><td><input type=text name=q value='" + queryString + "'></td></tr>");
		writer.println("<tr><td>Sort:</td><td><input type=text name=sort value='" + sort + "'></td></tr>");
		writer.println("<tr><td><input type=submit name=search value='" + queryString + "'></td></tr>");
		writer.println("</table>");
		writer.println("</form>");
		if (StringUtils.isNotBlank(queryString)) {
			SearchRequestUtil searchRequestUtil = new SearchRequestUtil(request, indexSchema);
			SearchRequest searchRequest = searchRequestUtil.getSearchRequest();
			SearchResponse searchResponse = mergeClient.search(searchRequest, timeoutState);
			CLong start = (CLong) searchResponse.start.clone();
			start.value++;
			writer.println("Results " + start + " - " + searchResponse.rows + " of " + searchResponse.numFound + " for " + htmlEscapedQueryString + "<br>");
			writer.println("<table border=0>");
			List<String> userFieldNames = indexSchema.getUserFieldNames();
			Collections.sort(userFieldNames);
			for (OceanDocument oceanDocument : searchResponse.oceanDocuments) {
				for (String userFieldName : userFieldNames) {
					List values = oceanDocument.getValues(userFieldName);
					if (values != null && values.size() > 0) {
						for (Object value : values) {
							writer.println("<tr>");
							writer.print("<td>" + userFieldName + "</td>");
							writer.print("<td>" + value + "</td>");
							writer.println("</tr>");
						}
					}
				}
				writer.println("<tr>");
				writer.print("<td>&nbsp;</td>");
				writer.println("</tr>");
			}
			writer.println("</table>");
		}
	}
}
